/*
 * many functions for unicode
 */

#include "common.h"
#include "statusbar.h"

/*****************************************************************************
 * Return a gunichar type char at the offset
 * Note: offset allows to pass a negative offset.
 *****************************************************************************/
gunichar
GetUnicodeChar(gchar * utf8_char, glong offset)
{
	g_return_val_if_fail(g_utf8_validate(utf8_char,-1, NULL),0);
	gchar * char_offset = g_utf8_offset_to_pointer(utf8_char, offset);
	return g_utf8_get_char(char_offset);
}


/*****************************************************************************
 * a utf-8 encoding string, return from ascii index to unicode index
 * @para  asciiIndex
 *        from 0 .. MAX_LINE_LEN * MAX_LINES
 *****************************************************************************/
glong
AsciiIndexToUTF8Index(const gchar *pText, // must be a utf-8 encoding string
                        glong asciiIndex)     // ascii index
{
    if ( NULL == pText || asciiIndex >= MAX_LINE_LEN * MAX_LINES )
        return 0;   // or -1 ??
    if ( strlen(pText) <= asciiIndex )
        return strlen(pText);
#ifdef HYPERSRC_DEBUG
    if ( !g_utf8_validate(pText,-1, NULL) )
    {
        PrintStatusbar("AsciiIndexToUTF8Index: involid utf8 str");
        return asciiIndex;
    }
#endif
    const gchar * p1 = pText + asciiIndex;
    glong utf8Index=0;
    utf8Index = g_utf8_pointer_to_offset(pText, p1);
    return utf8Index;
}

/*****************************************************************************
 * same as AsciiIndexToUTF8Index
 * @para  asciiIndex
 *        from 0 .. MAX_LINE_LEN * MAX_LINES
 *****************************************************************************/
glong
UTF8IndexToAsciiIndex(const gchar *pText, // must be a utf-8 encoding string
                        glong utf8Index)     // unicode index
{
    if ( NULL == pText || utf8Index >= MAX_LINE_LEN * MAX_LINES )
        return 0;   // maybe -1 better !
    if ( strlen(pText) <= utf8Index )
        return strlen(pText);
#ifdef HYPERSRC_DEBUG
    if ( !g_utf8_validate(pText,-1, NULL) )
    {
        PrintStatusbar("IndexToAsciiIndex :invalid utf8 str");
        return utf8Index;
    }
#endif
    gchar * p1 = g_utf8_offset_to_pointer(pText, utf8Index);
    glong asciiIndex= (glong)(p1 - pText);
    return asciiIndex;
}
